package com.sf.ams.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

/**
 * 描述：
 * 
 * <pre>HISTORY
 * ****************************************************************************
 *  ID   DATE           PERSON          REASON
 *  1    2017年10月26日      Simba.Hua         Create
 * ****************************************************************************
 * </pre>
 * @author Simba.Hua
 */
public class ZipRarUtil {
	private static final Logger logger = LoggerFactory.getLogger(ZipRarUtil.class);
	/**
	 * 解压zip包
	 * @param zipPath
	 * @param outputDirector
	 * @return
	 */
	public static boolean unZip(String zipPath,String outputDirectory) {
		File parent = new File(outputDirectory);
		if(parent.exists()){//有这个文件夹，则认为已经解压了
			return true;
		}
		ZipInputStream zipInput = null;
		FileInputStream fileInput = null;
		BufferedInputStream bufferInput = null;
		File outFile = null;
		ZipEntry entry = null;
		FileOutputStream fileOutputStream = null;
		BufferedOutputStream bufferedOutput = null;
		byte [] buff = new byte[1024];
		try {
			fileInput = new FileInputStream(new File(zipPath));
			zipInput = new ZipInputStream(fileInput);
			bufferInput = new BufferedInputStream(zipInput);
			
			while((entry = zipInput.getNextEntry()) != null) {
				if (entry.isDirectory()){
					return false;
				}
				outFile = new File(outputDirectory,entry.getName());
				if(!outFile.exists()){
					new File(outFile.getParent()).mkdirs();
				}
				fileOutputStream = new FileOutputStream(outFile);
				bufferedOutput = new BufferedOutputStream(fileOutputStream);
				int b = bufferInput.read(buff);
				while(b != -1) {
					bufferedOutput.write(buff,0,b);
					bufferedOutput.flush();
					b = bufferInput.read(buff);
				}
			}
			return true;
		} catch (FileNotFoundException e) {
			logger.error("FileNotFoundException",e);
		} catch (IOException e) {
			logger.error("IOException",e);
		} finally {
			try {
					if(bufferedOutput != null) bufferedOutput.close();
					if(fileOutputStream != null) fileOutputStream.close();
					if(bufferInput != null) bufferInput.close();
					if(fileInput != null) fileInput.close();
					
				} catch (IOException e) {
					logger.error("IOException",e);
				}
		}
		return false;
	}
	/**
	 * 解压rar文件
	 * @param rarFileName
	 * @param outputDirectory
	 * @return
	 */
	public static boolean unRar(String rarFileName,String outputDirectory) {
		File parent = new File(outputDirectory);
		if(parent.exists()){//有这个文件夹，则认为已经解压了
			return true;
		}
		Archive a = null;    
	    FileOutputStream fos = null;    
	    try{    
	        a = new Archive(new File(rarFileName));    
	        FileHeader fh = a.nextFileHeader();    
	        while(fh!=null){    
	            if(!fh.isDirectory()){    
	                //1 根据不同的操作系统拿到相应的 destDirName 和 destFileName    
	                String compressFileName = fh.getFileNameString().trim();    
	                String destFileName = "";    
	                String destDirName = "";    
	                //非windows系统    
	                if(File.separator.equals("/")){    
	                    destFileName = outputDirectory + File.separator + compressFileName.replaceAll("\\\\", "/");    
	                    destDirName = outputDirectory;   
	                //windows系统     
	                }else{    
	                    destFileName = outputDirectory + File.separator + compressFileName.replaceAll("/", "\\\\");    
	                    destDirName = outputDirectory;    
	                }    
	                //2创建文件夹    
	                File dir = new File(destDirName);    
	                if(!dir.exists()||!dir.isDirectory()){    
	                    dir.mkdirs();    
	                }    
	                //3解压缩文件    
	                fos = new FileOutputStream(new File(destFileName));    
	                a.extractFile(fh, fos);    
	                fos.close();    
	                fos = null;    
	            }    
	            fh = a.nextFileHeader();    
	        }    
	        a.close();    
	        a = null; 
	        return true;
	    }catch(Exception e){
	    	logger.error("unrar file {} fail",rarFileName,e);
		} finally {
			if (fos != null) {
				try {
					fos.close();
					fos = null;
				} catch (Exception e) {
					logger.error("Exception",e);
				}
			}
			if (a != null) {
				try {
					a.close();
					a = null;
				} catch (Exception e) {
					logger.error("Exception",e);
				}
			}
		} 
	    return false;
    }  
	
	//@Test
	public void testUnzip(){
		unRar("D:\\workspace_study\\automaticSql\\src\\main\\resources\\sqlfile\\UUPM\\file\\sql.rar",
				"D:\\workspace_study\\automaticSql\\src\\main\\resources\\sqlfile\\UUPM\\file\\sql");
	}
}
